var express = require("express");
var router = express.Router();
const connect = require("../public/javascripts/conn.js");
var crypto = require("crypto");

router.all("*", (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  next();
});

// 注册页面渲染
router.get("/", function (req, res, next) {
  res.render("register&login", { title: "注册" });
});
// 注册接口设置
router.post("/", function (req, res, next) {
  let data = req.body;
  /* // 模拟数据
  let data = {
    username: "123456",
    password: "123456",
  }; */
  // 对密码进行加密处理采用sha256加密，生成十六进制字符串
  data.password = crypto
    .createHmac("sha256", data.password)
    .update("secret password")
    .digest("hex");
  // 当密码为123456时，加密后的密码为：b946ccc987465afcda7e45b1715219711a13518d1f1663b8c53b848cb0143441
  
  // 查看当前用户名是否已经被注册
  connect.query(
    `select * from user where username = '${data.username}'`,
    (err, dat) => {
      if (err) {
        res.json({
          status: 0,
          msg: "数据库查询错误",
        });
      }
      // 返回的数据大于零说明该用户名已经被注册
      if (dat.length > 0) {
        res.json({
          status: 0,
          msg: "用户名已存在",
        });
      } else {
        connect.query(  //将账号密码插入数据库中
          `insert into user(username,password) values('${data.username}','${data.password}')`,
          (err, dat) => {
            if (err) {
              res.json({
                status: 0,
                msg: "数据库插入错误",
              });
            } else {
              res.json({
                status: 1,
                msg: "注册成功",
              });
            }
          }
        );
      }
    }
  );
});

module.exports = router;
